﻿using System;
using System.Linq;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;

namespace RibbonCustomization.RibbonPages
{
    public class DemoPage9
        : WebPartPage, IPostBackEventHandler
    {
        public const string TabWithToggleButtonID = "Ribbon.TabWithToggleButton";

        bool ToggleState
        {
            get { return (bool?)ViewState["ToggleState"] ?? false; }
            set { ViewState["ToggleState"] = value; }
        }

        void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
        {
            ToggleState = !ToggleState;
        }

        protected override void OnPreRender(EventArgs e)
        {
            SPRibbon ribbon = SPRibbon.GetCurrent(Page);
            if (ribbon != null)
            {
                ribbon.MakeTabAvailable(TabWithToggleButtonID);

                Page.ClientScript.RegisterStartupScript(
                    typeof(DemoPage8),
                    "DemoPage8",
                    ScriptLink.BuildDelayedExecutionScript(
                        "SamplePageComponentWithQuery.js",
                        "RibbonCustomization.SamplePageComponent.init") + ";", 
                    true);

                ScriptLink.RegisterScriptAfterUI(Page, "RibbonCustomization/SamplePageComponentWithQuery.js", false, true);

                RegisterCommands();
            }
            base.OnPreRender(e);
        }

        void RegisterCommands()
        {
            SPRibbonScriptManager scriptManager = new SPRibbonScriptManager();
            
            SPRibbonPostBackCommand command = new SPRibbonPostBackCommand(
                "Ribbon.TabWithToggleButton.DemoGroup.ServerSideToggleButton", this);
            SPRibbonQueryCommand queryCommand = new SPRibbonQueryCommand(
                "Ribbon.TabWithToggleButton.DemoGroup.ServerSideToggleButtonQuery", ToggleState); 

            scriptManager.RegisterHandleCommandFunction(this, "HandleSamplePageComponentWithPostbackCommand",
                new IRibbonCommand[] { command, queryCommand });

        }
    }
}
